package sys;
import java.sql.*;
import sys.BaseConnection;
import sys.Student;
public class UsersDao
{

    //
    Connection        conn=null;   //  负责连接数据库
    PreparedStatement  ps =null;   //  把sql语句提交到数据库执行
    ResultSet          rs =null;   // 获取select查询语句的结果

    BaseConnection baseDao=new BaseConnection();

    public boolean doLogin(Student stu)
    {   //处理登录
        boolean  bl = false ;
        conn = baseDao.getConnection();//1：获取数据库连接

        String sql="select * from studentdata where username=? and password=?";

        try {
            ps=conn.prepareStatement(sql);//2:提交sql语句到数据库上执行
            ps.setString(1, stu.getUserName());
            ps.setString(2, stu.getPassWord());
            rs=ps.executeQuery();// 3:获取查询的结果
            if(rs.next()){ // 指针
                bl=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(rs!=null){
                try {rs.close();} catch (Exception e2) {e2.printStackTrace();}
            }
            if(ps!=null){
                try {ps.close();} catch (Exception e2) {e2.printStackTrace();}
            }
            if(conn!=null){
                try {conn.close();} catch (Exception e2) {e2.printStackTrace();}
            }
        }

        return bl ;
    }

    public boolean addTo(Student stu)
    {   //处理登录
        boolean  bl = false ;
        conn = baseDao.getConnection();//1：获取数据库连接

        String sql="insert into studentdata(username,password) values (?,?)";

        try {
            ps=conn.prepareStatement(sql);//2:提交sql语句到数据库上执行
            ps.setString(1, stu.getUserName());
            ps.setString(2, stu.getPassWord());
            int count=ps.executeUpdate();// 3:获取查询的结果
            if(count==1){
                bl=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(rs!=null){
                try {rs.close();} catch (Exception e2) {e2.printStackTrace();}
            }
            if(ps!=null){
                try {ps.close();} catch (Exception e2) {e2.printStackTrace();}
            }
            if(conn!=null){
                try {conn.close();} catch (Exception e2) {e2.printStackTrace();}
            }
        }

        return bl ;
    }

}
